# -*- coding: utf-8 -*-
import csv
import json
import re
import tkinter as tk
from datetime import datetime, timedelta
from tqdm import tqdm
import requests

login_url = "http://e.arrowzl.cn/jterp/user/login"
token_url = "http://e.arrowzl.cn/jterp/user/loginByPhone"
token_1 = []
list_DDS = []
list_ID = []  # 空列表保存id
list_DDid = []  # 订单编号
list_SN = []  # 所有sn码，用来统计测试数量
list_SNs = []
list_Total = []  # 用来结算测试数量
timess = []


# 模拟登录发送验证码========================================================================================================
def get_yzm():
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0"}
    params = {"loginName": "冯教鸿", "password": "e10adc3949ba59abbe56e057f20f883e"}
    response = requests.post(login_url, json=params, headers=headers)
    data = response.json()
    if data.get("code") == 200:
        print("验证码发送成功,正在获取Token")
        token_1.append(data["data"]["token"])  # 提取token
        print(f'Token:\n{data["data"]["token"]}')
    else:
        print(f"验证码发送失败: {data.get('message', '未知错误')}")

    return token_1


# 登录系统，登录后才可以爬取不是直接用token就可以，是要后台保持登录状态============================================================ce25ee4a48714606acc851e0ed0ea88e_14
def log_in(m, tk):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0",
        "Referer": "http://e.arrowzl.cn/user/login",
        "Cookie": "x-hng=lang=zh-CN&domain=e.arrowzl.cn",  # 必须替换
        "Accept": "application/json, text/plain, */*",
        "Content-Type": "application/json;charset=UTF-8",
    }

    params1 = {
        "code": str(m),
        "token": tk
    }
    response = requests.post(token_url, json=params1, headers=headers)
    data = response.json()
    print("正在登录.....")
    if data.get("code") == 200:
        print("登录成功")
    else:
        print(f"登录失败: {data.get('message', '未知错误')}")


# 获取ID和订单号
def run_id(a, b, time):
    OKtime = f"{str(datetime.now().year)}" + time
    begintime = str(datetime.strptime(OKtime, "%Y%m%d").date())  # 开始日期
    endtime = str(datetime.strptime(OKtime, "%Y%m%d").date())  # 结束日期
    timess.append(begintime)
    timess.append(endtime)
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0",
        "Referer": "http://e.arrowzl.cn/bill/checkassemble",
        "Cookie": "x-hng=lang=zh-CN&domain=e.arrowzl.cn",  # 必须替换
        "X-Requested-With": "XMLHttpRequest",
        "Accept": "application/json, text/plain, */*",
        "Content-Type": "application/json;charset=UTF-8",
        "x-access-token": a
    }
    params = {
        "search": json.dumps({
            "type": "其它",
            "subType": "检测单",
            "roleType": "全部数据",
            "creator": b,
            "beginTime": begintime,  # 修改为要查询的日期
            "endTime": endtime}),
        "currentPage": 1,
        "pageSize": 20000
    }

    try:
        response = requests.Session().get(
            "http://e.arrowzl.cn/jterp/depotHead/list",
            headers=headers,
            params=params,
            timeout=10
        )
        if response.status_code == 200:  # 状态码为200说明访问成功
            data = response.text
            ids = re.findall(r'"id":\s*(\d+)', data)  # 提取id数值
            ddh = re.findall(r'"linkNumber":"([^"]*)"', data)  # 提取订单编号
            for i in range(len(ids)):
                list_ID.append(int(ids[i]))
            for i in range(len(ids)):
                list_DDid.append(str(ddh[i]))  # 保存订单编号进list

    except Exception as e:
        print("完整错误:", str(e))


def run_ok(a):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0",
        "Referer": "http://e.arrowzl.cn/bill/checkassemble",
        "Cookie": "x-hng=lang=zh-CN&domain=e.arrowzl.cn",  # 必须替换
        "X-Requested-With": "XMLHttpRequest",
        "Accept": "application/json, text/plain, */*",
        "Content-Type": "application/json;charset=UTF-8",
        "x-access-token": a
    }
    params2 = {
        "headerId": "614229",
        "mpList": "",
        "linkType": "basic"
    }
    try:
        for i in tqdm(range(len(list_ID)), desc="查询进度", position=0, colour='blue'):
            response = requests.session().get(
                f"http://e.arrowzl.cn/jterp/depotItem/getDetailList?headerId={list_ID[i]}&mpList=&linkType=basic",
                headers=headers,
                params=params2,
                timeout=30
            )
            if response.status_code == 200:
                data = response.text
                sns = re.findall(r'"snListSure":\s*"([^"]*)"', data)  # c955fbfba25340c7aa99e0b58dbec600_14
                dds = re.findall(r'"orderNumber":\s*"(\d+)', data)  # 提取snr'"snListSure":\s*"([^"]*)"'
                # ddname = re.findall(r'"standard":"([^"]*)', data)  # 提取snr'"snListSure":\s*"([^"]*)"'
                # print(ddname)
                # ddtype = re.findall(r'"categoryName":"([^"]*)', data)  # 提取snr'"snListSure":\s*"([^"]*)"'
                ddss = [int(x) for x in dds]
                for k in range(len(str(sns).split(","))):
                    list_SN.append(str(sns).split(",")[k])
                    list_Total.append(str(sns).split(",")[k])
                list_DDS.append(sum(ddss))
                list_SNs.append(len(list_SN))
                list_SN.clear()

    except Exception as e:
        print("完整错误:", str(e))
        exit()

if __name__ == '__main__':
    token = input('Token(没有就回车):')
    while 1:
        name_id = input('查谁(1me 2z 3s):')
        creator = 0
        if name_id == '1':
            creator = 13251
        elif name_id == '2':
            creator = 198
        elif name_id == '3':
            creator = 153
        if token == '':
            zzz = []
            get_yzm()
            yzm = input('手机验证码:\n')
            log_in(yzm, token_1[0])
            Otime = input('查询开始日期:\n')
            day_num = int(input('查询几天:\n'))
            for ys in range(day_num):  # 13251 198 1533f03387d5b5247009639a95587bdbdf2_14
                if int(Otime) < 1000:
                    run_id(token_1[0], creator, f'0{int(Otime) + ys}')
                    print(f'正在查询0{int(Otime) + ys}那天数据...')
                else:
                    run_id(token_1[0], creator, f'{int(Otime) + ys}')
                    print(f'正在查询{int(Otime) + ys}那天数据...')
                run_ok(token_1[0])
                print(f'===========\n总:{len(list_Total)}')
                zzz.append(len(list_Total))
                timess.clear()
                list_SNs.clear()
                list_DDS.clear()
                list_DDid.clear()
                list_ID.clear()
                list_Total.clear()
            print(sum(zzz))
        else:
            zzz = []
            Otime = input('查询开始日期:\n')
            day_num = int(input('查询几天:\n'))
            for ys in range(day_num):
                run_id(token, creator, f'{int(Otime) + ys}')
                print(f'正在查询0{int(Otime) + ys}那天数据...')
                run_ok(token)
                print(f'===========\n总:{len(list_Total)}')
                zzz.append(len(list_Total))
                timess.clear()
                list_SNs.clear()
                list_DDS.clear()
                list_DDid.clear()
                list_ID.clear()
                list_Total.clear()
            print(sum(zzz))
